import os, sys
import os.path as osp
import webp
import numpy as np
import cv2
from apnggif import apnggif
from PIL import Image
from apng import APNG


def convert(file_path):
  imgs = webp.load_images(file_path, mode="RGBA")
  print(len(imgs))
  print(type(imgs[0]))

def convert2(file_path):
  # Here it reads files in the folder input and sorts

  # Folder Creation for the output
  # Gets current working directory
  # Joins the folder that we wanted to create
  # creates the folder, and checks if it is created or not.

  # Iterates over the input images and saves them into output folder
  filenamePath = file_path + ".gif"
  apnggif(file_path, filenamePath)


def extract(file_path, save_dir):
  im = APNG.open(file_path)
  for i, (png, control) in enumerate(im.frames):
    png.save(osp.join(save_dir, "{i}.png".format(i=i)))

def compile(data_dir, width=582, height=466):
  imgs = []
  for i in range(0, 181):
    img = Image.open("{}/{}.png".format(data_dir, i))
    w,h = img.size
    diff = width - w
    new_img = Image.new('RGBA', (width, height), (255,255,255))
    new_img.paste(img, (diff//2, 0), img)
    print(new_img.size)
    imgs.append(new_img)

  webp.save_images(imgs, data_dir + ".webp", fps=25, quality=75, lossless=False)


if __name__ == "__main__":
  # file_path = sys.argv[1]
  # save_dir = sys.argv[2]

  # convert(file_path)
  # convert2(file_path)
  # extract(file_path, save_dir)

  data_dir = sys.argv[1]
  compile(data_dir)


"""
ffmpeg.exe -i in.png  -f gif out.gif
"""